import React, {useEffect, useState} from "react";
import {createStyles} from "antd-style"
import SystemInfoApi, {ProcessorInfo} from "@/api/web/SystemInfoApi.ts"
import EChartsFC from "@/components/EChartsFC.tsx";
import {EChartsOption, EChartsType} from "echarts";
import useThemeStore from "@/store/ThemeStore.ts";
import useAppState from "@/store/AppState.ts";
import {IThemeStoreData} from "@/store/LocalStore.ts";
import {Collapse} from "antd";

const doCpuUsageGraph = (ins: EChartsType, data: [number, number][], theme: IThemeStoreData) => {
    const option: EChartsOption = {
        backgroundColor: "transparent",
        textStyle: {
            color: theme.type == 'dark' ? "#ffffff" : "#000000",
        },
        color: ["#" + theme.color],
        title: [
            {
                text: "CPU使用率",
                left: "50%",
                top: "5%",
                textAlign: 'center',
                textStyle: {
                    color: theme.type == 'dark' ? "#ffffff" : "#000000",
                },
            },
        ],
        tooltip: {
            trigger: 'axis',
        },
        xAxis: {
            type: 'time',
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: 120,
            splitLine: {
                show: false,
            },
        },
        series: [{
            name: '数值',
            type: 'line',
            showSymbol: false,
            data: data,
            lineStyle: {
                width: 1.5,
            },
            itemStyle: {
                borderWidth: 1.5,
            },
        }],
    };

    ins.setOption(option)
}

const useStyles = createStyles(({css, token}) => {
    return {
        container: css`
            position: relative;
            height: auto;

            .info {
                position: absolute;
                left: 0;
                top: 0;
                height: 100%;
                width: 100%;
                overflow-y: auto;
                z-index: 20;
                transform: scaleY(0);
                background-color: ${token.colorBgContainer}3f;
                transition: all .2s;
            }

            .info-expand {
                transform: scaleY(100%);
            }
        `,
        infoCardContainer: css`
            padding: 16px;
            text-wrap: nowrap;
            
            .basic {
                li {
                    display: flex;
                    margin: 4px 0;
                    
                    span {
                        margin-left: auto;
                    }
                }
            }

            .features {
                margin-left: auto;
                text-align: right;
                height: 80px;
                padding: 8px;
                overflow: hidden auto;
            }
        `,
    }
})


interface Prop {
    info: ProcessorInfo
}

const ProcessorInfoCard: React.FC<Prop> = ({info}) => {
    const styles = useStyles().styles;
    const identifier = info.identifier;

    return (
        <div className={styles.infoCardContainer}>
            <ul className="basic">
                <li>名称<span>{identifier.name}</span></li>
                <li>物理核心数<span>{info.physicalProcessors.length}</span></li>
                <li>逻辑核心数<span>{info.logicalProcessors.length}</span></li>
                <li>处理器ID<span>{identifier.processorID}</span></li>
                <li>64位处理器<span>{identifier.cpu64bit ? "✓" : "✕"}</span></li>
                <li>制造商<span>{identifier.vendor}</span></li>
                <li>厂商频率<span>{identifier.vendorFreq}</span></li>
                <li>微架构名称<span>{identifier.microarchitecture}</span></li>
                <li>步进版本<span>{identifier.stepping}</span></li>
                <li>标识<span>{identifier.identifier}</span></li>
                <li>中断次数<span>{info.interrupts}</span></li>
                <li>支持特性
                    <ul className="features">{
                        info.featureFlags.map(item => (
                            <li key={item}>{item}</li>
                        ))
                    }</ul>
                </li>
            </ul>
        </div>
    )
}

const CpuInfoCard: React.FC = () => {
    const width = useAppState(state => state.width)
    const theme = useThemeStore(state => state.theme)
    const styles = useStyles().styles;
    const [cpuUsageList, setCpuUsageList] = useState<[number, number][]>([])
    const [processorInfo, setProcessorInfo] = useState<ProcessorInfo>()
    const [cpuUsageGraphInstance, setCpuUsageGraphInstance] = useState<EChartsType | null>(null)

    // 循环获取数据
    useEffect(() => {
        SystemInfoApi.getProcessorInfo().then(res => {
            setProcessorInfo(res.data)
        })

        let stop = false
        const loop = async () => {
            if (stop) {
                return
            }
            try {
                const res = await SystemInfoApi.getCpuInfo()
                setCpuUsageList(pre => {
                    pre.push([Date.now(), res.data.used])
                    if (pre.length > 20) pre.shift()
                    return [...pre]
                })
                setTimeout(loop, 1000)
            } catch (e) {
                console.error(e)
            }
        }

        loop().then()
        return () => {
            stop = true
        }
    }, []);

    useEffect(() => {
        if (cpuUsageGraphInstance == null) return
        doCpuUsageGraph(cpuUsageGraphInstance, cpuUsageList, theme)
    }, [cpuUsageList, cpuUsageGraphInstance, theme]);

    useEffect(() => {
        if (cpuUsageGraphInstance == null) return
        cpuUsageGraphInstance.resize({width: width})
    }, [width]);


    return (
        <div className={styles.container}>
            <EChartsFC width={width}
                       height={300}
                       graphInit={(ins) => setCpuUsageGraphInstance(ins)}
            />
            {processorInfo &&
                <Collapse
                    ghost
                    items={[{
                        key: "0",
                        label: "处理器信息",
                        styles: {
                            header: {fontSize: 17}
                        },
                        children: <ProcessorInfoCard info={processorInfo}/>
                    }]}
                />
            }
        </div>
    )
}

export default CpuInfoCard
